package com.ruoyi.common.utils.file;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

/**
 * 图片处理工具类
 *
 * @author ruoyi
 */
public class ImageUtils
{
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static byte[] getImage(String imagePath)
    {
        InputStream is = getFile(imagePath);
        try
        {
            return IOUtils.toByteArray(is);
        }
        catch (Exception e)
        {
            log.error("图片加载异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(is);
        }
    }

    public static InputStream getFile(String imagePath)
    {
        try
        {
            byte[] result = readFile(imagePath);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        }
        catch (Exception e)
        {
            log.error("获取图片异常 {}", e);
        }
        return null;
    }

    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(String url)
    {
        InputStream in = null;
        try
        {
            if (url.startsWith("http"))
            {
                // 网络地址
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(30 * 1000);
                urlConnection.setReadTimeout(60 * 1000);
                urlConnection.setDoInput(true);
                in = urlConnection.getInputStream();
            }
            else
            {
                // 本机地址
                String localPath = RuoYiConfig.getProfile();
                String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
                in = new FileInputStream(downloadPath);
            }
            return IOUtils.toByteArray(in);
        }
        catch (Exception e)
        {
            log.error("获取文件路径异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(in);
        }
    }

   /**
 * 保存 MultipartFile 到指定路径并返回文件的绝对路径
 *
 * @param file MultipartFile 对象
 * @return 文件的绝对路径
 * @throws IOException 如果保存文件时发生异常
 */
public static String saveFile(MultipartFile file) throws IOException {
    if (file == null || file.isEmpty()) {
        return null;
    }

    // 获取文件名和扩展名
    String originalFilename = file.getOriginalFilename();
    String fileExtName = StringUtils.substringAfterLast(originalFilename, ".");

    // 构建保存路径
    String localPath = RuoYiConfig.getProfile();
    String fileName = System.currentTimeMillis() + "." + fileExtName;
    String filePath = localPath + Constants.RESOURCE_PREFIX + fileName;

    // 将文件保存到本地
    File dest = new File(filePath);
    File parentDir = dest.getParentFile();
    if (!parentDir.exists()) {
        parentDir.mkdirs(); // 确保目录存在
    }
    file.transferTo(dest);

    // 返回文件的绝对路径
    return dest.getAbsolutePath();
}

}
